package com.grayscale.core.rule;

import com.grayscale.core.adapt.GrayScaleRuleAdapt;
import com.grayscale.core.enums.GrayScaleTypeEnum;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.math.BigDecimal;

/**
 * @author liuli
 * @date 2022/3/2
 * 数值类型比较 : 转成 BigDecimal 比较
 */
public class GrayScaleKeyNumberInterval implements GrayScaleRuleAdapt {
    private Logger log = LoggerFactory.getLogger(this.getClass());
    BigDecimal v1 = null;
    BigDecimal v2 = null;
    @Override
    public boolean process(String... parameter) {
        if (!check(parameter[0])){
            return false;
        }
        if (StringUtils.isBlank(parameter[3])){
            log.error("配置的KEY的值为空");
            return false;
        }
        BigDecimal keyNumber = null;
        try {
            keyNumber = new BigDecimal(parameter[3]);
        } catch (Exception e) {
            log.error("{} 转成数值类型失败",parameter[3]);
            return false;
        }
        GrayScaleTypeEnum grayScaleTypeEnum = GrayScaleTypeEnum.getByType(parameter[1]);
        switch (grayScaleTypeEnum) {
            case KEY_BETWEEN:
              if (keyNumber.compareTo(v1) == 1 && keyNumber.compareTo(v2) == -1){
                  return true;
              }
                break;
            case KEY_BETWEEN_DY:
                if (keyNumber.compareTo(v1) > -1 && keyNumber.compareTo(v2) < 1){
                    return true;
                }
                break;
            case KEY_OUTSIDE:
                if (keyNumber.compareTo(v1) == -1 || keyNumber.compareTo(v2) == 1){
                    return true;
                }
                break;
            case KEY_OUTSIDE_DY:
                if (keyNumber.compareTo(v1) < 1 || keyNumber.compareTo(v2) > -1){
                    return true;
                }
                break;
        }
        return false;
    }

    @Override
    public boolean check(String parameter) {
        try {
            v1 = new BigDecimal(parameter.split(",")[0]);
            v2 = new BigDecimal(parameter.split(",")[1]);
            if (v2.compareTo(v1) >-1){
                return true;
            }
            return  false;
        } catch (Exception e) {
            log.error("parameter format error:{} {}",parameter,e);
            return false;
        }
    }
}
